package com.leyou.order.utils;

import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayConfigImpl;
import com.leyou.common.exception.domain.LyException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 获取微信下单的支付链接
 */
@Slf4j
@Component
public class PayHelper {

    @Autowired
    private WXPayConfigImpl payConfig;

    @Autowired
    private WXPay wxPay;

    public String getPayUrl(Long orderId, Long totalFee){
        log.info("【微信统一下单工具类】开始！");
        // 请求参数：
        Map<String, String> data = new HashMap<String, String>();
        data.put("body", "乐优支付");
        data.put("out_trade_no", orderId.toString());
        data.put("total_fee", totalFee.toString());
        data.put("spbill_create_ip", "123.12.12.123");
        data.put("notify_url", payConfig.getNotifyUrl());
        data.put("trade_type", payConfig.getPayType());  // 此处指定为扫码支付

        try {
            Map<String, String> resp = wxPay.unifiedOrder(data);
            //验证微信返回结果是否正确
            checkResp(resp);
            log.info("【微信统一下单工具类】结束！");
            return resp.get("code_url");
        } catch (Exception e) {
            throw new LyException(502, "【微信统一下单工具类】异常！");
        }
    }

    public void checkResp(Map<String, String> resp) {
        //通信标识
        String returnCode = resp.get("return_code");
        if(!StringUtils.equals(returnCode, "SUCCESS")){
            log.error("【微信统一下单】通信异常！");
            throw new LyException(502, "【微信统一下单】通信异常！");
        }
        //业务标识
        String resultCode = resp.get("result_code");
        if(!StringUtils.equals(resultCode, "SUCCESS")){
            log.error("【微信统一下单】业务异常！异常信息为：{}", resp.get("err_code_des"));
            throw new LyException(502, "【微信统一下单】业务异常！");
        }
    }

}
